var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class LabelEditorPureCanvas {
    constructor() {
        this.userImageLib = {};
        this.LoadImageByUrl = LabelEditorPureCanvas_Other.prototype.LoadImageByUrl;
        this.waitForImageLoaded = LabelEditorPureCanvas_Other.prototype.waitForImageLoaded;
        this.GetTextColor = LabelEditorPureCanvas_Other.prototype.GetTextColor;
        this.HasInverset = LabelEditorPureCanvas_Other.prototype.HasInverset;
        this.SplitTxtByMaxWidth = LabelEditorPureCanvas_SplitTxtByMaxWidth.prototype.SplitTxtByMaxWidth;
    }
    templateToPngBase64(tpl, imgType, boardmodel) {
        var _a, _b;
        let backGroundColor = "#ffffff";
        if (((_a = boardmodel === null || boardmodel === void 0 ? void 0 : boardmodel.attr) === null || _a === void 0 ? void 0 : _a.LabelBackgroundColor) != undefined) {
            if (boardmodel.attr.LabelBackgroundColor.length > 2) {
                backGroundColor = boardmodel.attr.LabelBackgroundColor;
            }
        }
        let invertColorArea;
        if (((_b = boardmodel === null || boardmodel === void 0 ? void 0 : boardmodel.attr) === null || _b === void 0 ? void 0 : _b.LabelInverseColor) != undefined) {
            if (Array.isArray(boardmodel.attr.LabelInverseColor)) {
                if (boardmodel.attr.LabelInverseColor.length == 4) {
                    invertColorArea = boardmodel.attr.LabelInverseColor;
                }
            }
        }
        let paperWidth = tpl.attr.width;
        let paperHeight = tpl.attr.height;
        if (this.canvas == undefined) {
            this.canvas = document.createElement("canvas");
            this.canvas.width = paperWidth;
            this.canvas.height = paperHeight;
            this.ctx = this.canvas.getContext("2d");
        }
        return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
            this.ctx.clearRect(0, 0, paperWidth, paperHeight);
            this.ctx.fillStyle = backGroundColor;
            this.ctx.fillRect(0, 0, paperWidth, paperHeight);
            if (invertColorArea != undefined) {
                this.ctx.fillStyle = "#000000";
                this.ctx.fillRect(invertColorArea[0], invertColorArea[1], invertColorArea[2], invertColorArea[3]);
            }
            for (let i = 0; i < tpl.children.length; i++) {
                if (tpl.children[i].type == "TextBlock") {
                    let txt = tpl.children[i].value;
                    txt = this.replaceAll(txt, "undefined", "");
                    if (txt.trim().length == 0) {
                        continue;
                    }
                    let txtAttr = tpl.children[i].attr;
                    this.ctx.save();
                    this.ctx.fillStyle = this.GetTextColor(txtAttr, invertColorArea, tpl.children[i]);
                    let fontWeight = txtAttr.textStyle["font-weight"];
                    if (fontWeight == "none") {
                        fontWeight = "normal";
                    }
                    let xieTi = txtAttr.textStyle["font-style"];
                    if (xieTi == "normal" || xieTi == "none") {
                        xieTi = "";
                    }
                    let fontFamliy = "微软雅黑";
                    if (txtAttr.textStyle["font-family"] != undefined) {
                        fontFamliy = txtAttr.textStyle["font-family"];
                    }
                    this.ctx.font = xieTi + " " + fontWeight + " " + txtAttr.textStyle["font-size"] + " " + fontFamliy;
                    let fontSizeNum = parseFloat(txtAttr.textStyle["font-size"]);
                    let wordYPos = txtAttr.top + txtAttr.height;
                    if (txtAttr["vertical-align"] == "middle") {
                        this.ctx.textBaseline = 'middle';
                        wordYPos = txtAttr.top + txtAttr.height / 2;
                    }
                    else if (txtAttr["vertical-align"] == "top") {
                        this.ctx.textBaseline = 'top';
                        wordYPos = txtAttr.top;
                    }
                    else if (txtAttr["vertical-align"] == "bottom") {
                        this.ctx.textBaseline = 'bottom';
                        wordYPos = txtAttr.top + txtAttr.height;
                    }
                    let wordXPos = txtAttr.left;
                    if (txtAttr["text-align"] == "right") {
                        this.ctx.textAlign = "right";
                        wordXPos = txtAttr.left + txtAttr.width;
                    }
                    let txtList = txt.split("\n");
                    let txtMaxWidth = txtAttr.width;
                    let newTxtList = [];
                    for (let j = 0; j < txtList.length; j++) {
                        if (this.ctx.measureText(txtList[j]).width < txtMaxWidth) {
                            newTxtList.push(txtList[j]);
                        }
                        else {
                            newTxtList.push(...this.SplitTxtByMaxWidth(txtList[j], txtMaxWidth));
                        }
                    }
                    for (let j = 0; j < newTxtList.length; j++) {
                        this.ctx.fillText(newTxtList[j], wordXPos, wordYPos + fontSizeNum * j);
                    }
                    this.ctx.restore();
                }
                else if (tpl.children[i].type == "ImageBlock") {
                    let imageTop = tpl.children[i].attr.top;
                    let imageLeft = tpl.children[i].attr.left;
                    let imageWidth = tpl.children[i].attr.width;
                    let imageHeight = tpl.children[i].attr.height;
                    let imageHref = tpl.children[i].href;
                    if (imageHref.canvas == undefined) {
                        if (typeof imageHref == "string") {
                            let userImageNode;
                            let idName = "userImage" + imageHref.length;
                            if (this.userImageLib[idName] != undefined) {
                                userImageNode = this.userImageLib[idName];
                            }
                            else {
                                userImageNode = yield this.LoadImageByUrl(imageHref);
                                this.userImageLib[idName] = userImageNode;
                            }
                            this.ctx.drawImage(userImageNode, imageLeft, imageTop, imageWidth, imageHeight);
                        }
                        continue;
                    }
                    this.ctx.save();
                    if (tpl.children[i].value.indexOf("[$预览图左右镜像]") != -1) {
                        this.ctx.translate(imageWidth + imageLeft, imageTop);
                        this.ctx.scale(-1, 1);
                        this.ctx.drawImage(imageHref.canvas, 0, 0, imageWidth, imageHeight);
                    }
                    else if (tpl.children[i].value.indexOf("[$预览图上下镜像]") != -1) {
                        this.ctx.translate(imageLeft, imageTop + imageHeight);
                        this.ctx.scale(1, -1);
                        this.ctx.drawImage(imageHref.canvas, 0, 0, imageWidth, imageHeight);
                    }
                    else if (tpl.children[i].value.indexOf("[$预览图旋转180]") != -1) {
                        this.ctx.translate(imageLeft + imageWidth, imageTop + imageHeight);
                        this.ctx.scale(-1, -1);
                        this.ctx.drawImage(imageHref.canvas, 0, 0, imageWidth, imageHeight);
                    }
                    else {
                        this.ctx.drawImage(imageHref.canvas, imageLeft, imageTop, imageWidth, imageHeight);
                    }
                    imageHref.jcanvas.clear();
                    this.ctx.restore();
                }
                else if (tpl.children[i].type == "CodeBlock") {
                    let codeTop = tpl.children[i].attr.top;
                    let codeLeft = tpl.children[i].attr.left;
                    let codeWidth = tpl.children[i].attr.width;
                    let codeHeight = tpl.children[i].attr.height;
                    let codeValue = tpl.children[i].value;
                    if (tpl.children[i].type2 == "QRCode") {
                        let divElemnt = document.createElement('div');
                        let qrCode = new QRCode(divElemnt, {
                            text: codeValue,
                            width: codeWidth,
                            height: codeHeight,
                            colorDark: "#000000",
                            colorLight: "#ffffff",
                            correctLevel: QRCode.CorrectLevel.L,
                            typeNumber: 4
                        });
                        let codeImageNode = divElemnt.getElementsByTagName("img")[0];
                        codeImageNode = yield this.waitForImageLoaded(codeImageNode);
                        this.ctx.drawImage(codeImageNode, codeLeft, codeTop, codeWidth, codeHeight);
                        qrCode.clear();
                    }
                    else if (tpl.children[i].type2 == "DMCode") {
                        let dmCodeCanvas = document.createElement("canvas");
                        dmCodeCanvas.width = codeWidth;
                        dmCodeCanvas.height = codeHeight;
                        bwipjs.toCanvas(dmCodeCanvas, { "bcid": "datamatrix", "text": codeValue });
                        this.ctx.drawImage(dmCodeCanvas, codeLeft, codeTop, codeWidth, codeHeight);
                    }
                    else if (tpl.children[i].type2 == "BarCode") {
                        let barCodeCanvas = document.createElement("canvas");
                        barCodeCanvas.width = codeWidth;
                        barCodeCanvas.height = codeHeight;
                        bwipjs.toCanvas(barCodeCanvas, { "bcid": "code128", "text": codeValue });
                        this.ctx.drawImage(barCodeCanvas, codeLeft, codeTop, codeWidth, codeHeight);
                    }
                }
            }
            let returnBase64 = this.canvas.toDataURL('image/jpeg');
            returnBase64 = returnBase64.split(',')[1];
            requestAnimationFrame(() => {
                resolve(returnBase64);
            });
        }));
    }
    replaceAll(str, target, replace) {
        let raRegExp = new RegExp(target.toString().replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g, "\\$1"), "ig");
        str = str.toString().replace(raRegExp, replace.toString());
        return str;
    }
    Destroy() {
        this.userImageLib = {};
    }
}
class LabelEditorPureCanvas_Other {
    LoadImageByUrl(url) {
        return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
            let returnImage = new Image();
            returnImage.src = url;
            returnImage = yield this.waitForImageLoaded(returnImage);
            resolve(returnImage);
        }));
    }
    waitForImageLoaded(imageElement) {
        return new Promise((resolve, reject) => {
            imageElement.onload = () => {
                resolve(imageElement);
            };
            imageElement.onerror = () => {
                reject(new Error("图像加载失败"));
            };
        });
    }
    GetTextColor(txtAttr, invertColorArea, canKao) {
        if (invertColorArea == undefined) {
            let color = "#000000";
            if (txtAttr.color != undefined) {
                color = txtAttr.color;
            }
            if (txtAttr.opacity == undefined) {
                return color;
            }
            else {
                var charList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
                var theCharIndex = Math.round(txtAttr.opacity / (1 / charList.length));
                var theChar = charList[theCharIndex];
                return color + theChar + theChar;
            }
        }
        else {
            let L1 = txtAttr.left;
            let R1 = txtAttr.left + txtAttr.width;
            let T1 = txtAttr.top;
            let B1 = txtAttr.top + txtAttr.height;
            let L2 = invertColorArea[0];
            let R2 = invertColorArea[0] + invertColorArea[2];
            let T2 = invertColorArea[1];
            let B2 = invertColorArea[1] + invertColorArea[3];
            if (this.HasInverset(L1, R1, L2, R2) && this.HasInverset(T1, B1, T2, B2)) {
                return "#ffffff";
            }
            else {
                return "#000000";
            }
        }
    }
    HasInverset(min1, max1, min2, max2) {
        if (min2 < max1 && max1 < max2) {
            return true;
        }
        else if (min2 < min1 && min1 < max2) {
            return true;
        }
        else if (min1 < min2 && min2 < max1) {
            return true;
        }
        else if (min1 < max2 && max2 < max1) {
            return true;
        }
        return false;
    }
}
class LabelEditorPureCanvas_SplitTxtByMaxWidth {
    SplitTxtByMaxWidth(txt, maxWidth) {
        let returnTxtArray = [""];
        for (let i = 0; i < txt.length; i++) {
            returnTxtArray[returnTxtArray.length - 1] += txt[i];
            if (this.ctx.measureText(returnTxtArray[returnTxtArray.length - 1] + txt[i + 1]).width > maxWidth) {
                let leftTxt = txt.substring(i + 1);
                if (this.ctx.measureText(leftTxt).width < maxWidth) {
                    returnTxtArray.push(leftTxt);
                    break;
                }
                else {
                    returnTxtArray.push("");
                }
            }
        }
        if (returnTxtArray[returnTxtArray.length - 1].length == 0) {
            returnTxtArray.pop();
        }
        return returnTxtArray;
    }
}
